﻿using System.Drawing;
using System;
using System.Drawing.Imaging;
using System.Security.Cryptography;
using System.Text;

namespace SimpleQuartzTemplate.Controllers
{
	/// <summary>
	/// 接口名称 ：  VerifyCode
	/// 创 建 人 ：  dongming
	/// 创建时间 ：  2025/5/9 16:56:06 
	/// 描    述 ：  
	/// </summary>

	public static class VerifyCode
	{
		public static byte[] GenerateCaptchaImage(string captchaText, int width = 100, int height = 50)
		{
			Random random = new Random();
			using (Bitmap bitmap = new Bitmap(width, height))
			{
				using (Graphics g = Graphics.FromImage(bitmap))
				{
					g.Clear(Color.White);
					g.DrawString(captchaText, new Font("Arial", 24, FontStyle.Bold), Brushes.Black, new PointF(5, 5));

					// 添加一些噪点
					for (int i = 0; i < 20; i++)
					{
						int x1 = random.Next(bitmap.Width);
						int x2 = random.Next(bitmap.Width);
						int y1 = random.Next(bitmap.Height);
						int y2 = random.Next(bitmap.Height);
						g.DrawLine(new Pen(Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255))), x1, y1, x2, y2);
					}

					using (MemoryStream ms = new MemoryStream())
					{
						bitmap.Save(ms, ImageFormat.Png);
						return ms.ToArray();
					}
				}
			}
		}

		public static string GenerateRandomText(int length = 6)
		{
			const string valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			StringBuilder res = new StringBuilder();
			using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
			{
				char[] chars = new char[length];
				byte[] value = new byte[length * sizeof(char)];
				rng.GetBytes(value);
				Buffer.BlockCopy(value, 0, chars, 0, value.Length);
				foreach (char c in chars)
				{
					res.Append(valid[c % valid.Length]); //Suppose you want to generate a random string of a certain length and include uppercase letters and digits:

		}
			}
			return res.ToString();
		}
	}
}
